$(function() {
    var $image = $('#image')

    const options = {
        aspectRatio:1,

        preview:'.img-preview'
    }

    $('#image').cropper(options)
    
    $("#chooseImageBtn").on('click',function() {
        $("#chooseImageInp").click();
    })


    $("#chooseImageInp").on("change",function() {
        let file = this.files[0];

        if(file === undefined) {
            return layui.layer.msg('上传头像,不能为空!')
        }

        let url = URL.createObjectURL(file);
        console.log(url);

        $image.cropper("destroy")
            .attr('src',url)
            .cropper(options)
    })

    $("#uploadBtn").on('click',function() {
        var dataURL = $image
            .cropper('getCroppedCanvas', {
                width: 100,
                heigth:100
            })
            .toDataURL('image/png')
            
        axios({
            method:"POST",
            url:'/my/update/avatar',
            data:"avatar=" + encodeURIComponent(dataURL)
        }).then(res => {
            if(res.data.status !== 0) {
                return layui.layer.msg(res.data.message);
            }

            layui.layer.msg("恭喜您,更改用户头像成功")
            window.parent.getUserInfo();
        })    
            

    })

})